<script lang="ts" setup>
import type {HandCardsApi} from '#/api/spa/handcards';

import {h, onMounted, reactive, ref} from 'vue';

import {Page, useVbenModal} from '@vben/common-ui';
import {Download, Plus, Trash2} from '@vben/icons';
import type {VxeToolbarInstance} from '#/adapter/vxe-table';
import {
  cloneDeep,
  downloadFileFromBlobPart,
  formatDateTime,
  isEmpty,
} from '@vben/utils';

import {
  Button,
  Form,
  Input,
  message,
  Pagination,
  RangePicker,
  Select, SelectOption,
} from 'ant-design-vue';

import {VxeColumn, VxeTable, VxeToolbar,} from '#/adapter/vxe-table';
import {
  deleteHandCards,
  deleteHandCardsList,
  exportHandCards,
  getHandCardsPage,
} from '#/api/spa/handcards';
import {ContentWrap} from '#/components/content-wrap';
import {TableToolbar} from '#/components/table-toolbar';
import {useTableToolbar} from '#/hooks';
import {$t} from '#/locales';
import {DICT_TYPE, getDictOptions,getDictLabel, getRangePickerDefaultProps} from '#/utils';

import HandCardsForm from './modules/form.vue';
import {DICT_SPA_TYPE} from "#/utils/dictSpa";
import Tag from "#/views/ai/write/index/components/Tag.vue";
import {DictTag} from "#/components/dict-tag";

const loading = ref(true); // 列表的加载中
const list = ref<HandCardsApi.HandCards[]>([]); // 列表的数据

const total = ref(0); // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  cardNumber: undefined,
  cardType: undefined,
  status: undefined,
  teamId: undefined,
  roomNumber: undefined,
  openTime: undefined,
  totalConsumption: undefined,
  remarks: undefined,
  icon: undefined,
  createTime: undefined,
});
const queryFormRef = ref(); // 搜索的表单
const exportLoading = ref(false); // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = cloneDeep(queryParams) as any;
    if (params.openTime && Array.isArray(params.openTime)) {
      params.openTime = (params.openTime as string[]).join(',');
    }
    if (params.createTime && Array.isArray(params.createTime)) {
      params.createTime = (params.createTime as string[]).join(',');
    }
    const data = await getHandCardsPage(params);
    list.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: HandCardsForm,
  destroyOnClose: true,
});

/** 创建手牌管理 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑手牌管理 */
function handleEdit(row: HandCardsApi.HandCards) {
  formModalApi.setData(row).open();
}

/** 删除手牌管理 */
async function handleDelete(row: HandCardsApi.HandCards) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteHandCards(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_process_msg',
    });
    await getList();
  } finally {
    hideLoading();
  }
}

/** 批量删除手牌管理 */
async function handleDeleteBatch() {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting'),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteHandCardsList(checkedIds.value);
    message.success($t('ui.actionMessage.deleteSuccess'));
    await getList();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);

function handleRowCheckboxChange({
                                   records,
                                 }: {
  records: HandCardsApi.HandCards[];
}) {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出表格 */
async function onExport() {
  try {
    exportLoading.value = true;
    const data = await exportHandCards(queryParams);
    downloadFileFromBlobPart({fileName: '手牌管理.xls', source: data});
  } finally {
    exportLoading.value = false;
  }
}

const toolbarRef = ref<VxeToolbarInstance>()

const columnConfig = {
  drag: true,
  resizable: true
}
const rowConfig = {
  // drag: true,
  isCurrent: true,
  isHover: true
}

const cardTypeOptions = ref(getDictOptions(DICT_SPA_TYPE.HandCardType, 'number'))
const cardStatusOptions = ref(getDictOptions(DICT_SPA_TYPE.HandCardStatus, 'number'))
//

/** 初始化 */
const {hiddenSearchBar, tableToolbarRef, tableRef} = useTableToolbar();
onMounted(() => {
  getList();


});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="getList"/>

    <ContentWrap v-if="!hiddenSearchBar">
      <!-- 搜索工作栏 -->
      <Form :model="queryParams" ref="queryFormRef" layout="inline">
        <Form.Item label="手牌号码" name="cardNumber">
          <Input
            v-model:value="queryParams.cardNumber"
            placeholder="请输入手牌号码"
            allow-clear
            @press-enter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="手牌类型" name="cardType">
          <Select
            v-model:value="queryParams.cardType"
            placeholder="请选择手牌类型"
            allow-clear
            class="w-full"
          >
            <SelectOption
              v-for="(dict, index) in cardTypeOptions"
              :key="index"
              :value="dict.value"
            >
              {{ dict.label }}
            </SelectOption>
          </Select>

        </Form.Item>
        <Form.Item label="手牌状态" name="status">
          <Select
            v-model:value="queryParams.status"
            placeholder="请选择手牌状态"
            allow-clear
            class="w-full"
          >
            <SelectOption
              v-for="(dict, index) in cardStatusOptions"
              :key="index"
              :value="dict.value"
            >
              {{ dict.label }}
            </SelectOption>
          </Select>
        </Form.Item>
        <Form.Item label="团队ID" name="teamId">
          <Input
            v-model:value="queryParams.teamId"
            placeholder="请输入团队ID"
            allow-clear
            @press-enter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="房间号" name="roomNumber">
          <Input
            v-model:value="queryParams.roomNumber"
            placeholder="请输入房间号"
            allow-clear
            @press-enter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="开牌时间" name="openTime">
          <RangePicker
            v-model:value="queryParams.openTime"
            v-bind="getRangePickerDefaultProps()"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="总消费金额" name="totalConsumption">
          <Input
            v-model:value="queryParams.totalConsumption"
            placeholder="请输入总消费金额"
            allow-clear
            @press-enter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="备注信息" name="remarks">
          <Input
            v-model:value="queryParams.remarks"
            placeholder="请输入备注信息"
            allow-clear
            @press-enter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="图标标识" name="icon">
          <Input
            v-model:value="queryParams.icon"
            placeholder="请输入图标标识"
            allow-clear
            @press-enter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="创建时间" name="createTime">
          <RangePicker
            v-model:value="queryParams.createTime"
            v-bind="getRangePickerDefaultProps()"
            class="w-full"
          />
        </Form.Item>
        <Form.Item>
          <Button class="ml-2" @click="resetQuery"> 重置</Button>
          <Button class="ml-2" @click="handleQuery" type="primary">
            搜索
          </Button>
        </Form.Item>
      </Form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap title="手牌管理">
      <template #extra>
        <TableToolbar
          ref="tableToolbarRef"
          v-model:hidden-search="hiddenSearchBar"
        >
          <Button
            class="ml-2"
            :icon="h(Plus)"
            type="primary"
            @click="handleCreate"
            v-access:code="['spa:hand-cards:create']"
          >
            {{ $t('ui.actionTitle.create', ['手牌']) }}
          </Button>
          <Button
            :icon="h(Download)"
            type="primary"
            class="ml-2"
            :loading="exportLoading"
            @click="onExport"
            v-access:code="['spa:hand-cards:export']"
          >
            {{ $t('ui.actionTitle.export') }}
          </Button>
          <Button
            :icon="h(Trash2)"
            type="primary"
            danger
            class="ml-2"
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-access:code="['spa:hand-cards:delete']"
          >
            批量删除
          </Button>
        </TableToolbar>
      </template>
      <VxeTable
        ref="tableRef"
        :data="list"
        show-overflow
        :columnConfig="columnConfig"
        :rowConfig="rowConfig"
        :loading="loading"
        @checkbox-all="handleRowCheckboxChange"
        @checkbox-change="handleRowCheckboxChange"
      >
        <VxeColumn type="checkbox" width="40"/>
        <VxeColumn field="id" title="主键ID" align="center"/>
        <VxeColumn field="cardNumber" title="手牌号码" align="center"/>
        <VxeColumn field="cardType" title="手牌类型" align="center"  :filters="cardTypeOptions">
          <template #default="{ row }">
            <DictTag :value="row.cardType" :type="DICT_SPA_TYPE.HandCardType"></DictTag>
          </template>
        </VxeColumn>

        <VxeColumn field="status" title="手牌状态" align="center"  :filters="cardStatusOptions">
          <template #default="{ row }">
            <DictTag :value="row.status" :type="DICT_SPA_TYPE.HandCardStatus"></DictTag>
          </template>
        </VxeColumn>
        <VxeColumn field="teamId" title="团队ID" align="center"/>
        <VxeColumn field="roomNumber" title="房间号" align="center"/>
        <VxeColumn field="openTime" title="开牌时间" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.openTime) }}
          </template>
        </VxeColumn>
        <VxeColumn field="totalConsumption" title="总消费金额" align="center"/>
        <VxeColumn field="remarks" title="备注信息" align="center"/>
        <VxeColumn field="icon" title="图标标识" align="center"/>
        <VxeColumn field="createTime" title="创建时间" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </VxeColumn>
        <VxeColumn field="operation" title="操作" align="center">
          <template #default="{ row }">
            <Button
              size="small"
              type="link"
              @click="handleEdit(row as any)"
              v-access:code="['spa:hand-cards:update']"
            >
              {{ $t('ui.actionTitle.edit') }}
            </Button>
            <Button
              size="small"
              type="link"
              danger
              class="ml-2"
              @click="handleDelete(row as any)"
              v-access:code="['spa:hand-cards:delete']"
            >
              {{ $t('ui.actionTitle.delete') }}
            </Button>
          </template>
        </VxeColumn>
      </VxeTable>
      <!-- 分页 -->
      <div class="mt-2 flex justify-end">
        <Pagination
          :total="total"
          v-model:current="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          show-size-changer
          @change="getList"
        />
      </div>
    </ContentWrap>
  </Page>
</template>
